<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="structure_main">
    <div class="structure_left">
      <div class="left_title">模型基本信息</div>
      <el-form
        v-if="modelListType === 'add' || modelListType === 'modify'"
        ref="formRef"
        v-loading="loading"
        size="small"
        :rules="rules"
        :model="form"
        label-width="120px"
      >
        <el-form-item label="模型名称:" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" clearable :disabled="modelListType === 'view'" />
        </el-form-item>
        <el-form-item v-if="modelListType != 'add'" label="模型标识:" prop="id" required>
          <el-input v-model="form.id" clearable :disabled="modelListType !== 'add'" />
        </el-form-item>
        <el-form-item label="模型类型:" prop="modelType">
          <el-radio-group v-model="form.modelType" :disabled="modelListType === 'view' || isEditble" @change="handleModelTypeChange">
            <el-radio value="model">普通模型</el-radio>
            <el-radio value="common_model">通用模型</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型层级:" prop="modelHierarchy">
          <el-radio-group v-model="form.modelHierarchy" :disabled="modelListType === 'view' || isEditble" @change="handleModelHierarchy">
            <el-radio value="父级模型">父级模型</el-radio>
            <el-radio value="子级模型">子级模型</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="展示方式:" prop="showType">
          <el-radio-group v-model="form.showType">
            <el-radio value="tree">树型</el-radio>
            <el-radio v-if="form.modelHierarchy === '子级模型'" value="tag">标签</el-radio>
            <el-radio v-if="form.modelHierarchy === '子级模型'" value="table">表格</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="要素库" :prop="form.databaseTypeName ? 'databaseTypeName' : 'databasePath'">
          <el-cascader
            v-if="!form.databaseTypeName"
            ref="cascaderRef"
            v-model="form.databasePath"
            style="width: 100%"
            :options="databaseListCopy"
            placeholder="请选择要素数据库"
            :props="cascaderProps"
            :disabled="modelListType === 'view' || isEditble"
            @change="handleDatabaseChange"
          />
          <el-input v-else v-model="form.databaseTypeName" :disabled="true" />
        </el-form-item>
        <el-form-item label="业务场景" :prop="form.sceneName ? 'sceneName' : 'sceneId'">
          <el-select
            v-if="!form.sceneName"
            v-model="form.sceneId"
            placeholder="请选择业务场景"
            clearable
            :disabled="modelListType === 'view' || isEditble"
            @change="handleSceneChange"
          >
            <el-option v-for="item in businessScenariosList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
          <el-input v-else v-model="form.sceneName" :disabled="true" />
        </el-form-item>
        <el-form-item
          v-if="form.modelType === 'model'"
          label="业务系统"
          :prop="form.systemName ? 'systemName' : 'systemId'"
          @change="handleSystemChange"
        >
          <el-select
            v-if="!form.systemName"
            v-model="form.systemId"
            placeholder="请选择业务系统"
            :disabled="modelListType === 'view' || isEditble"
            clearable
          >
            <el-option v-for="item in businessSystemList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
          <el-input v-else v-model="form.systemName" :disabled="true" />
        </el-form-item>
        <el-form-item v-if="form.modelHierarchy === '父级模型'" label="版本号:" prop="versionNumber">
          <el-input v-model="form.versionNumber" placeholder="请输入版本号" clearable :disabled="modelListType === 'view'" />
        </el-form-item>
        <el-form-item v-if="form.modelHierarchy === '子级模型'" label="父级模型:" :prop="form.parentConfigName ? 'parentConfigName' : 'modelPath'">
          <el-cascader
            v-if="modelListType === 'modify' ? false : isEditble ? false : true"
            ref="modelCascader"
            v-model="form.modelPath"
            style="width: 100%"
            :options="parentModelList"
            placeholder="请选择父级模型"
            :props="modelCascaderProps"
            @change="parentModelChange"
          />
          <el-input v-else v-model="form.parentConfigName" :disabled="true" />
        </el-form-item>
        <el-form-item v-if="form.modelHierarchy === '子级模型'" label="父级模型元素:" prop="parentConfigFieldName">
          <el-select
            v-model="form.parentConfigFieldName"
            placeholder="请选择父级模型元素"
            clearable
            :disabled="modelListType === 'view'"
            @change="handleParentConfigChange"
          >
            <el-option v-for="item in parentFieldList" :key="item.id" :label="item.fieldName" :value="item.fieldName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型描述:" prop="description">
          <el-input
            v-model="form.description"
            placeholder="请输入模型描述"
            type="textarea"
            :autosize="{ minRows: 3 }"
            clearable
            :disabled="modelListType === 'view'"
          />
        </el-form-item>
      </el-form>
      <el-descriptions v-else class="pipe-descriptions" column="1">
        <el-descriptions-item label="模型名称：">{{ form.modelName }}</el-descriptions-item>
        <el-descriptions-item label="模型标识：">{{ form.id }}</el-descriptions-item>
        <el-descriptions-item label="模型类型：">{{ form.modelType === 'model' ? '普通模型' : '通用模型' }}</el-descriptions-item>
        <el-descriptions-item label="模型层级：">{{ form.parentConfigName ? '子级模型' : '父级模型' }}</el-descriptions-item>
        <el-descriptions-item label="展示方式：">{{
          form.showType === 'tree' ? '树型' : form.showType === 'tag' ? '标签' : '表格'
        }}</el-descriptions-item>
        <el-descriptions-item label="要素库：">{{ form.databaseTypeName }}</el-descriptions-item>
        <el-descriptions-item label="业务场景：">{{ form.sceneName }}</el-descriptions-item>
        <el-descriptions-item v-if="form.modelType === 'model'" label="业务系统：">{{ form.systemName }}</el-descriptions-item>
        <el-descriptions-item v-if="!form.parentConfigName" label="版本：">{{ form.versionNumber }}</el-descriptions-item>
        <el-descriptions-item v-if="form.parentConfigName" label="父级模型：">{{ form.parentConfigName }}</el-descriptions-item>
        <el-descriptions-item v-if="form.parentConfigFieldName" label="父级模型元素：">{{ form.parentConfigFieldName }}</el-descriptions-item>
        <el-descriptions-item label="模型描述：">{{ form.description }}</el-descriptions-item>
      </el-descriptions>
      <div v-if="modelListType === 'add' || modelListType === 'modify'" style="border-top: 1px solid #e6e6e6; margin-top: 15px; padding-top: 10px">
        <div style="margin-bottom: 10px; margin-left: 15px">
          <span class="title">通用字段选择</span> <span class="sub_title">注：请选择通用字段作为模型字段</span>
        </div>

        <el-form :inline="true" size="small" style="white-space: nowrap">
          <el-form-item style="width: 55%">
            <el-cascader
              ref="commonModelCascader"
              v-model="commonModelPath"
              style="width: 100%"
              :options="commonModelList"
              placeholder="请选择已创建的通用模型"
              :props="modelCascaderProps"
              @change="handleGeneralModelChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="search" @click="doQuery">查询</el-button>
            <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-table ref="commonFieldTableRef" :data="commonFieldList" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" />
            <el-table-column label="序号" align="center" width="60px" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字段名称" align="center" prop="fieldName" show-overflow-tooltip />
            <el-table-column label="字段中文名" align="center" prop="fieldChineseName" show-overflow-tooltip />
            <el-table-column label="数据类型" align="center" prop="fieldType" show-overflow-tooltip />
          </el-table>
        </div>
        <div class="left_button">
          <el-button v-if="modelListType !== 'view'" type="primary" size="default" @click="handleCommonField">
            选择 <el-icon><DArrowRight /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    <div class="model_display">
      <div class="model_title">模型内容</div>
      <el-card shadow="never" style="margin: 15px 15px; height: calc(100vh - 225px); overflow-y: auto; border-radius: 1px">
        <div>
          <el-table
            v-loading="loading"
            :data="form.fieldList"
            row-key="id"
            :expand-row-keys="expands"
            @expand-change="handleExpandChange"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="expand" align="center" width="25px">
              <template #default="scope">
                <div style="padding-left: 20px; padding-right: 20px">
                  <el-table
                    :data="scope.row.fieldList"
                    row-key="id"
                    :tree-props="{ children: 'fieldList', hasChildren: 'hasChildren' }"
                    default-expand-all
                    :row-class-name="subTableRowClassName"
                    border
                  >
                    <el-table-column label="序号" align="left" fixed="left" :width="widthCalc(scope.row.fieldList)">
                      <template #default="slotScope">
                        <span>{{ slotScope.row.indexPath }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" prop="fieldName">
                      <template #header> <span style="color: red">*</span>属性名称 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'"> {{ slotScope.row.fieldName }} </span>
                        <el-tooltip v-else :disabled="!slotScope.row.fieldName" effect="dark" :content="slotScope.row.fieldName" placement="top">
                          <el-input
                            v-model="slotScope.row.fieldName"
                            @blur="handleFieldBlur(slotScope.row)"
                            clearable
                            placeholder="请输入"
                            :class="{ 'error-border': slotScope.row.errorState.fieldName, 'ellipsis': true }"
                          ></el-input>
                        </el-tooltip>
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="fieldChineseName">
                      <template #header> <span style="color: red">*</span>属性中文名 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'"> {{ slotScope.row.fieldChineseName }} </span>
                        <el-tooltip
                          v-else
                          :disabled="!slotScope.row.fieldChineseName"
                          effect="dark"
                          :content="slotScope.row.fieldChineseName"
                          placement="top"
                        >
                          <el-input
                            v-model="slotScope.row.fieldChineseName"
                            clearable
                            placeholder="请输入"
                            :class="{ 'error-border': slotScope.row.errorState.fieldChineseName, 'ellipsis': true }"
                          ></el-input>
                        </el-tooltip>
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="fieldType">
                      <template #header> <span style="color: red">*</span>数据类型 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'"> {{ slotScope.row.fieldType }} </span>
                        <el-select
                          v-else
                          v-model="slotScope.row.fieldType"
                          clearable
                          placeholder="请选择"
                          :class="{ 'error-border': slotScope.row.errorState.fieldType }"
                          @change="handleFieldTypeChange(slotScope.row)"
                        >
                          <template v-if="slotScope.row.level === 3">
                            <el-option v-for="(value, key) in subFieldTypesListLevel3" :key="key" :label="value" :value="value"> </el-option>
                          </template>
                          <template v-else>
                            <el-option v-for="(value, key) in subFieldTypesList" :key="key" :label="value" :value="value"> </el-option>
                          </template>
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column label="默认值" align="center" prop="defaultValue">
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'"> {{ slotScope.row.defaultValue }} </span>
                        <el-tooltip
                          v-else
                          :disabled="!slotScope.row.defaultValue"
                          effect="dark"
                          :content="slotScope.row.defaultValue"
                          placement="top"
                        >
                          <el-input v-model="slotScope.row.defaultValue" clearable placeholder="请输入" :class="{ 'ellipsis': true }"></el-input>
                        </el-tooltip>
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="isKeyField">
                      <template #header> <span style="color: red">*</span> 是否为关键字 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'">
                          {{ slotScope.row.isKeyField === 1 ? '是' : '否' }}
                        </span>
                        <el-select v-else v-model="slotScope.row.isKeyField" placeholder="请选择">
                          <el-option :label="'是'" :value="1" />
                          <el-option :label="'否'" :value="0" />
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="isNullable">
                      <template #header> <span style="color: red">*</span> 是否允许为空 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'">
                          {{ slotScope.row.isNullable === 1 ? '是' : '否' }}
                        </span>
                        <el-select v-else v-model="slotScope.row.isNullable" placeholder="请选择">
                          <el-option :label="'是'" :value="1" />
                          <el-option :label="'否'" :value="0" />
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="isUnique">
                      <template #header> <span style="color: red">*</span> 是否唯一 </template>
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'">
                          {{ slotScope.row.isUnique === 1 ? '是' : '否' }}
                        </span>
                        <el-select v-else v-model="slotScope.row.isUnique" placeholder="请选择">
                          <el-option :label="'是'" :value="1" />
                          <el-option :label="'否'" :value="0" />
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column label="说明及备注" align="center" prop="fieldDescription">
                      <template #default="slotScope">
                        <span v-if="modelListType === 'view'"> {{ slotScope.row.fieldDescription }} </span>
                        <el-tooltip
                          v-else
                          :disabled="!slotScope.row.fieldDescription"
                          effect="dark"
                          :content="slotScope.row.fieldDescription"
                          placement="top"
                        >
                          <el-input v-model="slotScope.row.fieldDescription" clearable placeholder="请输入" :class="{ 'ellipsis': true }"></el-input>
                        </el-tooltip>
                      </template>
                    </el-table-column>

                    <el-table-column v-if="modelListType !== 'view'" label="操作" align="center" width="120" fixed="right">
                      <template #default="slotScope">
                        <el-button
                          v-if="modelListType !== 'view' && scope.row.fieldName !== 'create_by' && scope.row.fieldName !== 'create_time'"
                          size="small"
                          link
                          type="primary"
                          icon="Delete"
                          @click="handleDelete(slotScope.row)"
                          >删除</el-button
                        >
                        <el-button
                          v-if="
                            (slotScope.row.fieldType === '对象' || slotScope.row.fieldType === '列表') && modelListType !== 'view' && slotScope.row.level < 3
                          "
                          size="small"
                          icon="plus"
                          link
                          type="primary"
                          @click="handleAddEvent(slotScope.row)"
                        >
                          添加子属性
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="序号" align="center" width="50px">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="fieldName">
              <template #header> <span style="color: red">*</span> 字段名称 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'"> {{ scope.row.fieldName }} </span>
                <el-tooltip v-else :disabled="!scope.row.fieldName" effect="dark" :content="scope.row.fieldName" placement="top">
                  <el-input
                    v-model="scope.row.fieldName"
                    @blur="handleFieldBlur(scope.row)"
                    clearable
                    placeholder="请输入"
                    :class="{ 'error-border': scope.row.errorState.fieldName, 'ellipsis': true }"
                    :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                  ></el-input>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="fieldChineseName">
              <template #header> <span style="color: red">*</span> 字段中文名 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'"> {{ scope.row.fieldChineseName }} </span>
                <el-tooltip v-else :disabled="!scope.row.fieldChineseName" effect="dark" :content="scope.row.fieldChineseName" placement="top">
                  <el-input
                    v-model="scope.row.fieldChineseName"
                    clearable
                    placeholder="请输入"
                    :class="{ 'error-border': scope.row.errorState.fieldChineseName, 'ellipsis': true }"
                    :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                  ></el-input>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="fieldType">
              <template #header> <span style="color: red">*</span> 数据类型 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'"> {{ scope.row.fieldType }} </span>
                <el-select
                  v-else
                  v-model="scope.row.fieldType"
                  clearable
                  placeholder="请选择"
                  :class="{ 'error-border': scope.row.errorState.fieldType, 'ellipsis': true }"
                  :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time' || scope.row.isRelated === 1"
                  @change="handleFieldTypeChange(scope.row)"
                >
                  <el-option v-for="(value, key) in fieldTypesList" :key="key" :label="value" :value="value"> </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="默认值" align="center" prop="defaultValue">
              <template #default="scope">
                <span v-if="modelListType === 'view'"> {{ scope.row.defaultValue || '-' }} </span>
                <el-tooltip v-else :disabled="!scope.row.defaultValue" effect="dark" :content="scope.row.defaultValue" placement="top">
                  <el-input
                    v-model="scope.row.defaultValue"
                    clearable
                    placeholder="请输入"
                    :class="{ 'ellipsis': true }"
                    :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                  ></el-input>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="isKeyField">
              <template #header> <span style="color: red">*</span> 是否为关键字 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'">
                  {{ scope.row.isKeyField === 1 ? '是' : '否' }}
                </span>
                <el-select
                  v-else
                  v-model="scope.row.isKeyField"
                  placeholder="请选择"
                  :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                >
                  <el-option :label="'是'" :value="1" />
                  <el-option :label="'否'" :value="0" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="isNullable">
              <template #header> <span style="color: red">*</span> 是否允许为空 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'">
                  {{ scope.row.isNullable === 1 ? '是' : '否' }}
                </span>
                <el-select
                  v-else
                  v-model="scope.row.isNullable"
                  placeholder="请选择"
                  :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                >
                  <el-option :label="'是'" :value="1" />
                  <el-option :label="'否'" :value="0" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="isUnique">
              <template #header> <span style="color: red">*</span> 是否唯一 </template>
              <template #default="scope">
                <span v-if="modelListType === 'view'">
                  {{ scope.row.isUnique === 1 ? '是' : '否' }}
                </span>
                <el-select
                  v-else
                  v-model="scope.row.isUnique"
                  placeholder="请选择"
                  :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                >
                  <el-option :label="'是'" :value="1" />
                  <el-option :label="'否'" :value="0" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="说明及备注" align="center" prop="fieldDescription">
              <template #default="scope">
                <span v-if="modelListType === 'view'"> {{ scope.row.fieldDescription || '-' }} </span>
                <el-tooltip v-else :disabled="!scope.row.fieldDescription" effect="dark" :content="scope.row.fieldDescription" placement="top">
                  <el-input
                    v-model="scope.row.fieldDescription"
                    clearable
                    placeholder="请输入"
                    :class="{ 'ellipsis': true }"
                    :disabled="scope.row.fieldName === 'create_by' || scope.row.fieldName === 'create_time'"
                  ></el-input>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="140" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    v-if="modelListType !== 'view' && scope.row.fieldName !== 'create_by' && scope.row.fieldName !== 'create_time'"
                    size="small"
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                  <el-button
                    v-if="modelListType === 'view' && scope.row.isRelated"
                    size="small"
                    link
                    type="primary"
                    icon="View"
                    @click="handleView(scope.row)"
                    >查看关联模型</el-button
                  >
                  <el-button
                    v-if="(scope.row.fieldType === '对象' || scope.row.fieldType === '列表') && modelListType !== 'view'"
                    size="small"
                    link
                    type="primary"
                    icon="edit"
                    @click="handleAddEvent(scope.row)"
                  >
                    添加属性
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="display: flex; justify-content: center; margin-top: 10px">
          <el-button v-if="modelListType !== 'view'" type="primary" size="small" icon="Plus" style="width: 220px" @click="addRow()">
            新增参数
          </el-button>
        </div>
      </el-card>

      <div class="model_button">
        <el-button size="small" @click="handleVisible()">{{ modelListType === 'view' ? '返回' : '取消' }}</el-button>
        <el-button v-if="modelListType !== 'view'" size="small" type="primary" @click="submitAdd"> 保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getModellTreeByBusiness, getModellTree, getModelDetail, saveElementModel, getFieldTypes } from '@/api/metaData/model.ts';
const props = defineProps(['addVisible', 'rowData', 'modelListType', 'modelId', 'nodeId', 'cardScrollTop']);
const emits = defineEmits(['handleEvent']);
const { proxy } = getCurrentInstance();
const modelListType = props.modelListType;
// 数据库
const treeData = ref([]);
const databaseList = ref([]);
const databaseListCopy = ref([]);
const cascaderRef = ref();
const cascaderProps = ref({
  value: 'id',
  label: 'databaseName',
  children: 'children',
  checkStrictly: true
});

// 业务场景,业务系统
const businessSystemList = ref([]);
const businessScenariosList = ref([]);
// 父模型;
const modelCascader = ref();
const modelCascaderProps = ref({
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true
});
// 通用模型
const commonModelPath = ref([]);
const commonModelCascader = ref();
const commonModelList = ref([]);

// 添加属性弹窗
const addDialogVisible = ref(false);
const operateType = ref('');
const subRowData = ref([]);

const isEditble = ref(false);
const formRef = ref();
const form = ref({
  id: props.rowData?.id || '',
  fieldList:
    props.modelListType === 'add'
      ? [
          {
            fieldList: [],
            fieldName: 'create_time',
            fieldChineseName: '数据的添加时间',
            fieldType: '时间戳',
            fieldDescription: '数据的添加时间',
            defaultValue: '',
            isKeyField: 0,
            isNullable: 1,
            isUnique: 0,
            errorState: {
              fieldName: false,
              fieldChineseName: false,
              fieldType: false
            }
          },
          {
            fieldList: [],
            fieldName: 'create_by',
            fieldChineseName: '数据的创建人',
            fieldType: '整型',
            fieldDescription: '数据的创建人',
            defaultValue: '',
            isKeyField: 0,
            isNullable: 1,
            isUnique: 0,
            errorState: {
              fieldName: false,
              fieldChineseName: false,
              fieldType: false
            }
          }
        ]
      : [],
  databasePath: [],
  modelPath: [],
  nodeId: props.rowData?.nodeId || '',
  parentConfigId: props.rowData?.parentModelId || '',
  parentConfigName: props.rowData?.parentConfigName || '',
  modelHierarchy: '',
  systemId: props.rowData?.systemId || '',
  sceneId: props.rowData?.sceneId || '',
  databaseTypeId: props.rowData?.databaseTypeId || '',
  systemName: props.rowData?.systemName || '',
  sceneName: props.rowData?.sceneName || '',
  databaseTypeName: props.rowData?.databaseTypeName || ''
});
if (props.rowData) {
  if (props.rowData.parentConfigName) {
    form.value.modelHierarchy = '子级模型';
  } else {
    form.value.modelHierarchy = '父级模型';
  }
} else {
  form.value.modelHierarchy = '';
}
if (props.rowData) {
  if (props.rowData.hasOwnProperty('isEditble')) {
    isEditble.value = props.rowData.isEditble;
  }
}
const parentModelList = ref([]);
const parentFieldList = ref();
const generalModelId = ref('');
const commonFieldList = ref([]);
const expands = ref([]);
const loading = ref(true);
const selectedFields = ref([]);
const commonFieldTableRef = ref();
const fieldTypesList = ref({});
const subFieldTypesList = ref({});
const subFieldTypesListLevel3 = ref({});
const pathStack = ref([]);

const addErrorStateToFieldList = (fields) => {
  return fields.map((item) => ({
    ...item,
    errorState: {
      fieldName: false,
      fieldChineseName: false,
      fieldType: false
    },
    fieldList: item.fieldList ? addErrorStateToFieldList(item.fieldList) : item.fieldList
  }));
};

const rules = {
  databasePath: [{ required: true, message: '请选择所属要素库', trigger: 'blur' }],
  modelPath: [{ required: true, message: '请选择父级模型', trigger: 'blur' }],
  parentConfigFieldName: [{ required: true, message: '请选择父级字段', trigger: 'blur' }],
  modelName: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  versionNumber: [{ required: true, message: '请输入父级版本', trigger: 'blur' }],
  modelType: [{ required: true, message: '请选择模型类型', trigger: 'blur' }],
  modelHierarchy: [{ required: true, message: '请选择模型层级', trigger: 'blur' }],
  systemId: [{ required: true, message: '请选择业务系统', trigger: 'blur' }],
  sceneId: [{ required: true, message: '请选择业务场景', trigger: 'blur' }],
  showType: [{ required: true, message: '请选择展示类型', trigger: 'blur' }],
  databaseTypeName: [{ required: true, message: '请选择要素库', trigger: 'blur' }],
  sceneName: [{ required: true, message: '请选择业务场景', trigger: 'blur' }],
  systemName: [{ required: true, message: '请选择业务系统', trigger: 'blur' }]
};

// 监听要素数据库,业务场景和业务系统的变化
const updateModelLists = () => {
  const { databaseTypeId, sceneId, systemId } = form.value;
  form.value.modelPath = [];
  if (databaseTypeId && sceneId && !systemId) {
    getModellTreeByBusiness({ databaseTypeId, sceneId }).then((response) => {
      if (response.code === 200) {
        parentModelList.value = response.data?.children || [];
        form.value.nodeId = response.data?.id || '';
        form.value.nodeName = response.data?.name || '';
        commonModelList.value = response.data?.children || [];
      }
    });
  } else if (databaseTypeId && sceneId && systemId) {
    getModellTreeByBusiness({ databaseTypeId, sceneId, systemId }).then((response) => {
      if (response.code === 200) {
        form.value.nodeId = response.data?.id || '';
        form.value.nodeName = response.data?.name || '';
        parentModelList.value = response.data?.children || [];
      }
    });
    getModellTreeByBusiness({ databaseTypeId, sceneId }).then((response) => {
      if (response.code === 200) {
        commonModelList.value = response.data?.children || [];
      }
    });
  } else {
    parentModelList.value = [];
  }
};

watch(() => [form.value.databaseTypeId, form.value.sceneId, form.value.systemId], updateModelLists, { immediate: true });

// 获取要素库节点数据
const findDatabaseBussisinessIdByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findDatabaseBussisinessIdByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 处理树结构，筛选出业务场景库树结构
const filterBusinessScenarios = (node) => {
  if (node.type === 'scene') {
    const newNode = { id: node.id, businessId: node.businessId, name: node.name, type: node.type, children: node.children };
    return newNode;
  }
  return null;
};

// 要素库变更
const handleDatabaseChange = (valueArr) => {
  form.value.sceneId = '';
  form.value.systemId = '';
  form.value.parentConfigId = '';
  form.value.parentConfigName = '';
  form.value.parentConfigFieldId = '';
  form.value.parentConfigFieldName = '';
  parentFieldList.value = [];
  form.value.modelPath = [];
  cascaderRef.value.togglePopperVisible(false);
  const foundNode = findDatabaseBussisinessIdByIds(treeData.value, valueArr);
  if (foundNode) {
    form.value.databaseTypeId = foundNode.businessId;
  }
  // 处理树结构，筛选出业务场景树结构
  const filterBusinessScenariosList = foundNode.children.map((node) => filterBusinessScenarios(node)).filter((node) => node !== null);
  businessScenariosList.value = filterBusinessScenariosList.map((node) => ({
    id: node.businessId,
    name: node.name,
    type: node.type,
    children: node.children
  }));
};

// 处理树结构，筛选出业务系统树结构
const filterBusinessSystems = (node) => {
  if (node.type === 'system') {
    const newNode = { id: node.id, businessId: node.businessId, name: node.name, type: node.type, children: node.children };
    return newNode;
  }
  return null;
};

// 业务场景更改
const handleSceneChange = (value) => {
  form.value.systemId = '';
  const selectedNode = businessScenariosList.value.find((item) => item.id === value);
  const filterBusinessSystemsList = selectedNode.children.map((node) => filterBusinessSystems(node)).filter((node) => node !== null);
  businessSystemList.value = filterBusinessSystemsList.map((node) => ({
    id: node.businessId,
    name: node.name,
    type: node.type,
    children: node.children
  }));
};

// 业务系统更改
const handleSystemChange = (value) => {
  const foundNode = findDatabaseBussisinessIdByIds(treeData.value, [value]);
  if (foundNode) {
    form.value.systemId = foundNode.businessId;
  }
};

// 获取级联选择器节点数据
const findNodeByIds = (nodes, ids) => {
  for (const node of nodes) {
    if (node.id === ids[ids.length - 1]) {
      return node;
    }
    if (node.children) {
      const foundNode = findNodeByIds(node.children, ids);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
};

// 监听模型类型变化
const handleModelTypeChange = (value) => {
  form.value.systemId = '';
  form.value.parentConfigId = '';
  form.value.parentConfigName = '';
  form.value.parentConfigFieldId = '';
  form.value.parentConfigFieldName = '';
  parentFieldList.value = [];
  form.value.modelPath = [];
};

// 监听模型层级变化
const handleModelHierarchy = () => {
  form.value.modelPath = [];
  form.value.versionNumber = '';
  form.value.parentConfigId = '';
  form.value.parentConfigName = '';
  form.value.parentConfigFieldId = '';
  form.value.parentConfigFieldName = '';
};

// 处理父模型数据
const parentModelChange = (value) => {
  modelCascader.value.togglePopperVisible(false);
  parentFieldList.value = [];
  form.value.parentConfigId = '';
  form.value.parentConfigName = '';
  form.value.parentConfigFieldId = '';
  form.value.parentConfigFieldName = '';
  const selectedNode = findNodeByIds(parentModelList.value, value);
  form.value.parentConfigId = selectedNode.id;
  form.value.parentConfigName = selectedNode.name;
  const ids = {
    id: form.value.parentConfigId
  };
  getModelDetail(ids).then((res) => {
    if (res.code === 200) {
      parentFieldList.value = res.data.fieldList
        .map((item) => {
          // 过滤已经关联好的字段
          if (item.fieldType !== '模型' || item.fieldName === 'time' || item.fieldName === 'createBy' || item.isRelated === 1) {
            return undefined;
          }
          return {
            id: item.id,
            fieldName: item.fieldName
          };
        })
        .filter((item) => item);
      if (parentFieldList.value.length === 0) {
        form.value.parentConfigId = '';
        form.value.parentConfigName = '';
        form.value.parentConfigFieldId = '';
        form.value.parentConfigFieldName = '';
        form.value.modelPath = [];
        ElMessageBox.alert('该模型没有可关联的字段，请选择其他模型或在该模型中添加 "模型" 类型的字段', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
      }
    }
  });
};

const handleParentConfigChange = (selectedFieldName) => {
  const selectedField = parentFieldList.value.find((item) => item.fieldName === selectedFieldName);
  if (selectedField) {
    form.value.parentConfigFieldId = selectedField.id;
  }
};

// 监控通用模型选则
const handleGeneralModelChange = (valueArr) => {
  commonModelCascader.value.togglePopperVisible(false);
  generalModelId.value = valueArr[valueArr.length - 1];
};

// 整理通用字段
const doQuery = () => {
  const params = {
    id: generalModelId.value
  };
  if (params.id) {
    getModelDetail(params).then((res) => {
      if (res.code === 200) {
        commonFieldList.value = res.data.fieldList
          .map((item) => {
            if (item.fieldName === 'time' || item.fieldName === 'createBy') {
              return undefined;
            }
            return {
              fieldName: item.fieldName,
              fieldChineseName: item.fieldChineseName,
              fieldType: item.fieldType,
              fieldList: item?.fieldList || [],
              fieldDescription: item.fieldDescription,
              defaultValue: item.defaultValue,
              isKeyField: item.isKeyField,
              isNullable: item.isNullable,
              isUnique: item.isUnique
            };
          })
          .filter((item) => item);
      }
    });
  }
};

const resetQuery = () => {
  commonModelPath.value = [];
  generalModelId.value = '';
  commonFieldList.value = [];
};

// 选择通用字段
const handleSelectionChange = (selectedRows) => {
  selectedFields.value = selectedRows.sort((a, b) => {
    return commonFieldList.value.findIndex((item) => item.id === a.id) - commonFieldList.value.findIndex((item) => item.id === b.id);
  });
};

// 处理通用字段
const handleCommonField = () => {
  const uneditableSelectedFields = selectedFields.value.map((item) => {
    return {
      fieldList: addErrorStateToFieldList(item.fieldList),
      fieldName: item.fieldName,
      fieldChineseName: item.fieldChineseName,
      fieldType: item.fieldType,
      fieldDescription: item.fieldDescription,
      defaultValue: item.defaultValue,
      isKeyField: item.isKeyField,
      isNullable: item.isNullable,
      isUnique: item.isUnique,
      errorState: {
        fieldName: false,
        fieldChineseName: false,
        fieldType: false
      }
    };
  });
  form.value.fieldList.push(...uneditableSelectedFields);
  selectedFields.value.forEach((field) => {
    commonFieldTableRef.value.toggleRowSelection(field, false);
  });
};

// 处理主表格新增
const addRow = () => {
  const newRow = {
    id: `new-id-${Date.now()}`,
    fieldList: [],
    fieldName: '',
    fieldChineseName: '',
    fieldType: '',
    fieldDescription: '',
    defaultValue: '',
    isKeyField: 0,
    isNullable: 1,
    isUnique: 0,
    errorState: {
      fieldName: false,
      fieldChineseName: false,
      fieldType: false
    }
  };
  form.value.fieldList.push(newRow);
};

// 类型改变重置子表格数据
const handleFieldTypeChange = (data) => {
  data.fieldList = [];
  collapseRow(data);
};

const widthCalc = (data) => {
  const getMaxLevel = (nodes) => {
    return nodes.reduce((max, node) => {
      const nodeLevel = node.level || 1; // 优先使用节点自身层级
      const childLevel = node.fieldList ? getMaxLevel(node.fieldList) : 0;
      return Math.max(max, nodeLevel, childLevel);
    }, 0);
  };

  const maxLevel = getMaxLevel(data);
  return maxLevel >= 3 ? 130 : maxLevel === 2 ? 100 : 60;
};

// 递归计算层级和序号
const calculateLevelAndIndex = (data, parentIndex = '') => {
  return data.map((item, index) => {
    // 设置当前节点层级
    item.level = parentIndex ? parentIndex.split('.').length : 0;

    // 生成组合序号
    item.indexPath = parentIndex ? `${parentIndex}.${index + 1}` : `${index + 1}`;

    if (item.fieldList && item.fieldList.length > 0) {
      // 递归处理子节点（传递当前节点序号）
      item.fieldList = calculateLevelAndIndex(item.fieldList, item.indexPath);
    }
    return item;
  });
};

// 添加属性
const handleAddEvent = (targetNode) => {
  expandRow(targetNode);
  // 创建新的字段对象
  const newRow = {
    id: `new-id-${Date.now()}`,
    fieldList: [],
    fieldName: '',
    fieldChineseName: '',
    fieldType: '',
    fieldDescription: '',
    defaultValue: '',
    isKeyField: 0,
    isNullable: 1,
    isUnique: 0,
    errorState: {
      fieldName: false,
      fieldChineseName: false,
      fieldType: false
    }
  };
  // 递归查找目标节点
  const addToTree = (nodes, targetId) => {
    for (const node of nodes) {
      // 找到目标节点
      if (node.id === targetId) {
        if (!node.fieldList) {
          node.fieldList = []; // 初始化子列表
        }
        node.fieldList.push(newRow);
        return true;
      }
      // 递归搜索子节点
      if (node.fieldList && node.fieldList.length > 0) {
        if (addToTree(node.fieldList, targetId)) {
          return true; // 已找到并添加，提前返回
        }
      }
    }
    return false;
  };

  // 执行递归添加
  const success = addToTree(form.value.fieldList, targetNode.id);

  // 如果操作成功，更新层级序号
  if (success) {
    form.value.fieldList = calculateLevelAndIndex(JSON.parse(JSON.stringify(form.value.fieldList)));
  }
};
// 删除字段
const handleDelete = (row) => {
  const removeFromTree = (nodes, targetId) => {
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      // 找到目标节点
      if (node.id === targetId) {
        if (!node.isRelated) {
          nodes.splice(i, 1); // 删除该节点
          return true;
        } else {
          ElMessageBox.alert('本条数据已经关联子模型，请先删除子模型后尝试', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {});
          return false; // 如果节点已关联子模型，则不删除并返回false
        }
      }
      // 如果节点有子节点，则递归搜索子节点
      if (node.fieldList && node.fieldList.length > 0) {
        if (removeFromTree(node.fieldList, targetId)) {
          return true; // 已找到并删除子节点，提前返回
        }
      }
    }
    return false; // 没有找到目标节点
  };

  removeFromTree(form.value.fieldList, row.id);
  form.value.fieldList = calculateLevelAndIndex(JSON.parse(JSON.stringify(form.value.fieldList)));
};

// 展开行
const expandRow = (row) => {
  if (!expands.value.includes(row.id)) {
    expands.value.push(row.id);
  }
  row.isExpanded = true;
};

// 折叠行
const collapseRow = (row) => {
  if (expands.value.includes(row.id)) {
    expands.value = expands.value.filter((val) => val !== row.id);
  }
  row.isExpanded = false;
};

const handleExpandChange = (expandedRows) => {
  // 记录展开的行id
  console.log('expandedRows', expandedRows);
  if (!expands.value.includes(expandedRows.id)) {
    expands.value.push(expandedRows.id);
  }
};

// 已关联字段高亮展示以及展开折叠按钮展示
const tableRowClassName = ({ row }) => {
  let className = '';

  if (row.isRelated === 1) {
    className += 'highlight-blue ';
  }

  if ((row.fieldType === '对象' || row.fieldType === '列表') && row.fieldList && row.fieldList.length > 0) {
    className += 'has-expand-icon '; // 自定义类名用于显示展开图标
  }

  // 去除末尾的空格并返回
  return className.trim();
};
// 子表格展开折叠按钮展示
const subTableRowClassName = ({ row }) => {
  let className = '';

  if ((row.fieldType === '对象' || row.fieldType === '列表') && row.fieldList && row.fieldList.length > 0) {
    className += 'has-expand-icon '; // 自定义类名用于显示展开图标
  }

  // 去除末尾的空格并返回
  return className.trim();
};

// 查看子模型详情
const handleView = (data) => {
  const nextId = data.relatedModelId;
  pathStack.value.push(form.value.id); // 记录当前模型ID
  form.value.id = nextId;
  getList(nextId);
};

// 刷新数据或向父组件发出信号控制弹窗的隐藏
const handleVisible = () => {
  if (pathStack.value.length > 0) {
    const previousModelId = pathStack.value.pop();
    form.value.id = previousModelId;
    getList(previousModelId);
  } else {
    emits('handleEvent', { component: 'modelList', modelId: props.modelId, nodeId: props.nodeId, cardScrollTop: props.cardScrollTop });
  }
};

// 单独校验字段名是否合法
const handleFieldBlur = (row) => {
  // 保留字段校验
  if (['create_time', 'create_by'].includes(row.fieldName)) {
    row.fieldName = '';
    row.errorState.fieldName = true;
    proxy?.$modal.msgError('禁止使用保留字段名称,已自动清空');
    return;
  } else {
    row.errorState.fieldName = false;
  }
  // 递归查找父节点和同级节点
  const findSiblings = (fields, target, path = []) => {
    for (const [index, item] of fields.entries()) {
      if (item === target) {
        return { siblings: fields };
      }
      if (item.fieldList) {
        const result = findSiblings(item.fieldList, target, [...path, item]);
        if (result) return result;
      }
    }
    return null;
  };
  // 执行同级校验（修复版）
  const { siblings } = findSiblings(form.value.fieldList, row) || {};
  if (siblings) {
    // 统计所有字段名（包含当前字段）
    const nameMap = new Map();
    siblings.forEach((item) => {
      if (item.fieldName) {
        nameMap.set(item.fieldName, (nameMap.get(item.fieldName) || 0) + 1);
      }
    });

    // 标记所有重复字段
    let hasDuplicate = false;
    siblings.forEach((item) => {
      if (nameMap.get(item.fieldName) > 1) {
        item.errorState.fieldName = true;
        hasDuplicate = true;
      } else {
        item.errorState.fieldName = false;
      }
    });

    // 显示错误提示
    if (hasDuplicate && nameMap.get(row.fieldName) > 1) {
      proxy?.$modal.msgError(`同级存在重复字段名: ${row.fieldName}`);
    }
  }
};

// 整体校验字段
const validateFields = () => {
  let isValid = true;
  let hasEmptyField = false;

  // 递归查找所有有效字段（排除create_by和create_time）
  const filterValidFields = (fields) => {
    return fields.flatMap((item) => {
      const children = item.fieldList ? filterValidFields(item.fieldList) : [];
      return item.fieldName !== 'create_by' && item.fieldName !== 'create_time' ? [item, ...children] : children;
    });
  };

  const validFields = filterValidFields(form.value.fieldList);
  if (validFields.length === 0) {
    proxy?.$modal.msgError('必须至少包含一个非创建人/创建时间的字段');
    isValid = false;
  }

  // 递归校验必填项
  const checkFieldsRecursive = (fields) => {
    fields.forEach((item) => {
      item.errorState.fieldType = false;
      item.errorState.fieldChineseName = false;

      // 校验必填项
      let isEmpty = false;

      if (!item.fieldName) {
        item.errorState.fieldName = true;
        isEmpty = true;
      }

      if (!item.fieldChineseName) {
        item.errorState.fieldChineseName = true;
        isEmpty = true;
      }

      if (!item.fieldType) {
        item.errorState.fieldType = true;
        isEmpty = true;
      }

      if (isEmpty) {
        hasEmptyField = true;
        isValid = false;
      }

      // 递归校验子字段
      if (item.fieldList) {
        checkFieldsRecursive(item.fieldList);
      }
    });
  };

  checkFieldsRecursive(form.value.fieldList);
  if (hasEmptyField) {
    proxy?.$modal.msgError('字段集合必填项不能为空');
  }

  return isValid;
};

// 表单提交
const submitAdd = () => {
  formRef.value.validate((valid) => {
    const fieldsValid = validateFields();
    function checkErrorState(fields) {
      let isValid = true;
      fields.forEach((item) => {
        if (item.errorState.fieldName === true) {
          isValid = false;
        }
        if (item.children && item.children.length > 0) {
          isValid = checkErrorState(item.children) && isValid;
        }
      });
      return isValid;
    }
    if (!valid || !fieldsValid || !checkErrorState(form.value.fieldList)) {
      return;
    } else {
      // 创建一个用于提交的新对象，防止直接修改原对象
      let submitForm = JSON.parse(JSON.stringify(form.value));
      // 过滤掉 fieldName 为 'create_time' 和 'create_by' 的字段
      submitForm.fieldList = submitForm.fieldList.filter((item) => item.fieldName !== 'create_time' && item.fieldName !== 'create_by');
      // 递归去除所有子表格的errorState
      const clearErrorState = (fields) => {
        fields.forEach((item) => {
          delete item.errorState;
          if (item.fieldList && item.fieldList.length > 0) {
            clearErrorState(item.fieldList);
          }
        });
      };
      clearErrorState(submitForm.fieldList);
      // 去掉级联选择器路径
      delete submitForm.databasePath;
      delete submitForm.modelPath;

      if (modelListType === 'add') {
        const clearIds = (fields) => {
          fields.forEach((item) => {
            item.id = '';
            if (item.fieldList && item.fieldList.length > 0) {
              clearIds(item.fieldList);
            }
          });
        };

        clearIds(submitForm.fieldList);
        saveElementModel(submitForm).then((res) => {
          if (res?.code === 200) {
            emits('handleEvent', { component: 'modelList', modelId: props.modelId, nodeId: props.nodeId, cardScrollTop: props.cardScrollTop });
            proxy?.$modal.msgSuccess('新增成功');
          }
        });
      } else if (modelListType === 'modify') {
        const clearIds = (fields) => {
          fields.forEach((item) => {
            if (item.id && item.id.startsWith('new-id-')) {
              item.id = '';
            }
            if (item.fieldList && item.fieldList.length > 0) {
              clearIds(item.fieldList);
            }
          });
        };

        clearIds(submitForm.fieldList);
        saveElementModel(submitForm).then((res) => {
          if (res?.code === 200) {
            emits('handleEvent', {
              component: 'modelList',
              modelId: props.modelId,
              nodeId: props.nodeId,
              cardScrollTop: props.cardScrollTop
            });
            proxy?.$modal.msgSuccess('修改成功');
          }
        });
      }
    }
  });
};

// 处理树结构，筛选出要素库树结构
const extractNodes = (node) => {
  if (node.type === 'database_1' || node.type === 'database_2') {
    const newNode = { id: node.id, businessId: node.businessId, databaseName: node.name, type: node.type, children: node.children };
    if (node.children && node.children.length > 0) {
      newNode.children = node.children.map((child) => extractNodes(child)).filter((child) => child !== null); // 过滤掉 null 值
    }
    return newNode;
  }
  return null;
};

const getList = (data) => {
  loading.value = true;
  if (modelListType === 'add') {
    if (props.rowData?.modelParentType == 'common_model') {
      form.value.modelType = 'common_model';
    }
    if (props.rowData?.modelParentType == 'model') {
      form.value.modelType = 'model';
    }
  }
  const params = { id: '' };
  if (data) {
    params.id = data;
  } else if (form.value.id) {
    params.id = form.value.id;
  } else if (props.rowData?.parentModelId) {
    params.id = props.rowData.parentModelId;
  }
  if (params.id !== '') {
    getModelDetail(params).then((res) => {
      if (res.code === 200) {
        form.value.modelName = props.rowData?.parentModelId ? '' : res.data.modelName;
        form.value.modelType = res.data.modelType;
        form.value.nodeId = res.data.nodeId;
        form.value.nodeName = res.data.nodeName;
        form.value.versionNumber = props.rowData?.parentModelId ? (modelListType === 'modify' ? res.data.modelName : '') : res.data.versionNumber;
        form.value.parentConfigId = props.rowData?.parentModelId ? res.data.id : res.data.parentConfigId;
        form.value.parentConfigName = props.rowData?.parentModelId ? res.data.modelName : res.data.parentConfigName;
        form.value.parentConfigFieldName = props.rowData?.parentModelId ? '' : res.data.parentConfigFieldName;
        form.value.parentConfigFieldId = props.rowData?.parentModelId ? '' : res.data.parentConfigFieldId;
        form.value.databaseTypeId = res.data.databaseTypeId;
        form.value.databaseTypeName = res.data.databaseTypeName;
        form.value.description = props.rowData?.parentModelId ? '' : res.data.description;
        form.value.sceneId = res.data.sceneId;
        form.value.sceneName = res.data.sceneName;
        form.value.systemId = res.data.systemId;
        form.value.systemName = res.data.systemName;
        form.value.showType = props.rowData?.parentModelId ? (modelListType === 'modify' ? res.data.modelName : '') : res.data.showType;
        form.value.fieldList = props.rowData?.parentModelId
          ? modelListType === 'modify'
            ? addErrorStateToFieldList(res.data?.fieldList || [])
            : []
          : addErrorStateToFieldList(res.data?.fieldList || []);
        if (modelListType === 'add') {
          form.value.modelHierarchy = props.rowData?.parentModelId ? '子级模型' : '父级模型';
        } else if (modelListType === 'modify' || modelListType === 'view') {
          form.value.modelHierarchy = res.data.parentConfigId ? '子级模型' : '父级模型';
        }

        nextTick(() => {
          form.value.fieldList = calculateLevelAndIndex(JSON.parse(JSON.stringify(form.value.fieldList)));
          // 更新父模型字段列表数据
          const parentModelParams = {
            id: form.value.parentConfigId || ''
          };
          if (parentModelParams.id) {
            getModelDetail(parentModelParams).then((parentRes) => {
              if (parentRes.code === 200) {
                parentFieldList.value = parentRes.data.fieldList
                  .map((item) => {
                    // 过滤已经关联好的字段
                    if (item.fieldType !== '模型' || item.fieldName === 'time' || item.fieldName === 'createBy' || item.isRelated === 1) {
                      return undefined;
                    }
                    return {
                      id: item.id,
                      fieldName: item.fieldName
                    };
                  })
                  .filter((item) => item);
              }
            });
          }
        });
      }
      console.log('form.value', form.value);
      form.value.fieldList.unshift(
        {
          fieldList: [],
          fieldName: 'create_time',
          fieldChineseName: '数据的添加时间',
          fieldType: '时间戳',
          fieldDescription: '数据的添加时间',
          defaultValue: '',
          isKeyField: 0,
          isNullable: 1,
          isUnique: 0,
          errorState: {
            fieldName: false,
            fieldChineseName: false,
            fieldType: false
          }
        },
        {
          fieldList: [],
          fieldName: 'create_by',
          fieldChineseName: '数据的创建人',
          fieldType: '整型',
          fieldDescription: '数据的创建人',
          defaultValue: '',
          IsKeyField: 0,
          isNullable: 1,
          isUnique: 0,
          errorState: {
            fieldName: false,
            fieldChineseName: false,
            fieldType: false
          }
        }
      );
    });
  }
  getFieldTypes().then((res) => {
    if (res?.code === 200) {
      fieldTypesList.value = res?.data || {};
      subFieldTypesList.value = fieldTypesList.value.filter((item) => item !== '模型');
      subFieldTypesListLevel3.value = fieldTypesList.value.filter((item) => item !== '模型' && item !== '对象' && item !== '列表');
    }
  });
  getModellTree().then((res) => {
    if (res.code === 200) {
      treeData.value = res.data.children || [];
      // 筛选出要素库树结构
      databaseList.value = treeData.value.map((node) => extractNodes(node)).filter((node) => node !== null);
      databaseListCopy.value = JSON.parse(JSON.stringify(databaseList.value));
    }
  });
  loading.value = false;
};

onMounted(() => {
  getList();
  updateModelLists();
});
</script>

<style lang="scss" scoped>
.pipe-descriptions {
  margin-left: 20px;
  :deep(.el-descriptions__body .el-descriptions__table .el-descriptions__cell) {
    word-break: break-all;
    word-wrap: break-word;
  }
}
.structure_main {
  display: flex;
  .structure_left {
    width: 25%;
    height: calc(100vh - 84px);
    border-right: 1px solid #d9d9d9;
    padding: 5px 15px 20px 15px;
    overflow-y: auto;
    .left_title {
      height: 60px;
      line-height: 60px;
      padding: 0 40px;
      margin: 0px 0px 15px 0px;
      border: 1px solid #d9d9d9;
      font-size: 20px;
    }
    .title {
      font-size: 16px;
      font-weight: bold;
      height: 20px;
      line-height: 20px;
      color: #606266;
      margin-right: 10px;
    }
    .sub_title {
      font-size: 14px;
      height: 15px;
      line-height: 15px;
      color: #909399;
    }
    .left_button {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
  .model_display {
    width: 75%;
    height: calc(100vh - 84px);
    overflow: auto;
    .model_title {
      height: 60px;
      line-height: 60px;
      padding: 0 40px;
      margin: 5px 15px 5px 15px;
      border: 1px solid #d9d9d9;
      font-size: 20px;
    }
    .error-border {
      :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px #f56c6c inset;
      }
      :deep(.el-select__wrapper) {
        box-shadow: 0 0 0 1px #f56c6c inset;
      }
    }
    .ellipsis {
      :deep(.el-input__inner) {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .el-table {
      :deep(.highlight-blue) {
        --el-table-tr-bg-color: var(--el-color-primary-light-9);
      }
      :deep(.has-expand-icon .el-table__expand-icon) {
        display: inline-block !important;
      }
      :deep(.el-table__expand-icon) {
        display: none;
      }
    }

    .model_button {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>
